package com.house.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.common.Result;
import com.house.dao.UserMapper;
import com.house.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户模块服务层
 */
@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper, User> {


    /**
     * 注册
     * @param user
     * @return
     */
    public Result register(User user) {

        // 验证用户名是否已存在
        if(queryByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在！");
        }

        // 密码加密入库
        user.setPassword(SecureUtil.md5(user.getPassword()));

        // 角色默认为普通用户
        user.setRole("normal");
        user.setCreateTime(DateUtil.now());
        user.setUpdateTime(DateUtil.now());
        baseMapper.insert(user);

        return Result.ok(user);
    }


    /**
     * 通过用户名查询用户
     * @param username
     * @return
     */
    public User queryByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("username", username);

        return baseMapper.selectOne(wrapper);
    }

}
